package com.sz.android;

/**
 * prepare
 * loop
 * myLooper
 *
 *
 */
public class Looper {
    //通知等待
    //MesssageQueue  blockinigqueue，阻塞队列

    MessageQueue mQueue;

    private Looper(){
        mQueue = new MessageQueue();
    }

    //线程绑定
    static ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();

    public static void prepare(){
        if (sThreadLocal.get() != null){
            throw new RuntimeException("已经prepare过");
        }
        sThreadLocal.set(new Looper());
    }

    public static Looper myLooper(){
        return sThreadLocal.get();
    }

    public static void loop(){
        System.out.println("Looper.loop start");
        Looper looper = Looper.myLooper();
        MessageQueue lQueue = looper.mQueue;

        for (;;){
            Message message = lQueue.next();
            if (message != null){
                message.target.dispatchMessage(message);
            }else {
//                System.out.println("message null,让出时间片");
//                Thread.yield();
            }
        }
    }
}
